package com.music.note_android.ui.search

import android.content.Context
import android.content.SharedPreferences
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow

class SearchHistoryManager(context: Context) {
    
    private val sharedPreferences: SharedPreferences = 
        context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
    
    private val _searchHistory = MutableStateFlow<List<String>>(emptyList())
    val searchHistory: StateFlow<List<String>> = _searchHistory.asStateFlow()
    
    init {
        loadSearchHistory()
    }
    
    fun addSearchQuery(query: String) {
        if (query.isBlank()) return
        
        val currentHistory = _searchHistory.value.toMutableList()
        
        // 移除已存在的相同查询
        currentHistory.remove(query)
        
        // 添加到列表开头
        currentHistory.add(0, query)
        
        // 限制历史记录数量
        if (currentHistory.size > MAX_HISTORY_SIZE) {
            currentHistory.removeAt(currentHistory.size - 1)
        }
        
        _searchHistory.value = currentHistory
        saveSearchHistory(currentHistory)
    }
    
    fun removeSearchQuery(query: String) {
        val currentHistory = _searchHistory.value.toMutableList()
        currentHistory.remove(query)
        _searchHistory.value = currentHistory
        saveSearchHistory(currentHistory)
    }
    
    fun clearSearchHistory() {
        _searchHistory.value = emptyList()
        sharedPreferences.edit().clear().apply()
    }
    
    private fun loadSearchHistory() {
        val historySet = sharedPreferences.getStringSet(KEY_SEARCH_HISTORY, emptySet()) ?: emptySet()
        val historyList = historySet.toList().take(MAX_HISTORY_SIZE)
        _searchHistory.value = historyList
    }
    
    private fun saveSearchHistory(history: List<String>) {
        sharedPreferences.edit()
            .putStringSet(KEY_SEARCH_HISTORY, history.toSet())
            .apply()
    }
    
    companion object {
        private const val PREFS_NAME = "search_history_prefs"
        private const val KEY_SEARCH_HISTORY = "search_history"
        private const val MAX_HISTORY_SIZE = 10
    }
}